﻿namespace ufida.u9.ait.openapi
{
	using System;
	using System.Collections.Generic;
	using System.Text;
    using ufida.u9.ait.openapi.utils;
    using UFIDA.U9.Base;
    using UFIDA.U9.Base.Organization;
    using UFIDA.U9.CBO.HR.Department;
    using UFIDA.U9.CBO.HR.Operator;
    using UFIDA.U9.CBO.SCM.Customer;
    using UFIDA.U9.CBO.SCM.ProjectTask;
    using UFIDA.U9.SM.SC;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Business;
    using UFSoft.UBF.Util.Context;

	/// <summary>
	/// ProjectSaveSV partial 
	/// </summary>	
	public partial class ProjectSaveSV 
	{	
		internal BaseStrategy Select()
		{
			return new ProjectSaveSVImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class ProjectSaveSVImpementStrategy : BaseStrategy
	{
		public ProjectSaveSVImpementStrategy() { }

		public override object Do(object obj)
		{						
			ProjectSaveSV bpObj = (ProjectSaveSV)obj;
            try
            {
				if (bpObj.Data == null || bpObj.Data.Count == 0)
					throw new Exception("传入参数为空");
				List<CopyOfCommonArchiveDataDTOData> retlist = new List<CopyOfCommonArchiveDataDTOData>();
				foreach (var dto in bpObj.Data)
                {
					Project entity = Project.Finder.Find($"Code='{dto.Code}' and Org={Context.LoginOrg.ID}");
                    dto.Org = new CopyOfCommonArchiveDataDTOData
                    {
                        ID = Context.LoginOrg.ID,
                        Code = Context.LoginOrg.Code,
                    };

                    if (entity == null)
                    {
						//创建项目档案
						entity=CreateProject(dto);
                    }
                    else
                    {
						//修改项目档案
						entity=UpdateProject(entity, dto);
                    }

                    //处理返回值
                    retlist.Add(new CopyOfCommonArchiveDataDTOData
                    {
                        ID = entity.ID,
                        Code = entity.Code,
                        Name = entity.Name,
                    });
                }

				return ResultUtils.success(bpObj, bpObj.Data, retlist);
			}
			catch(Exception ex)
            {
				return ResultUtils.error(bpObj, bpObj.Data, ex);
			}
		}

        private Project UpdateProject(Project entity, AITProjectDTOData dto)
        {
            using(ISession session = Session.Open())
            {
                SetValue(dto, entity);
                session.Commit();
            }
			return entity;
        }

        private Project CreateProject(AITProjectDTOData dto)
        {
			Project entity = Project.Create();
            using(ISession session = Session.Open())
            {
                SetValue(dto, entity);

                session.Commit();
            }

            return entity;
        }

        private static void SetValue(AITProjectDTOData dto, Project entity)
        {
            entity.Code = dto.Code;
            entity.Name = dto.Name;
            if (String.IsNullOrEmpty(dto.StartDate))
                entity.StartDate = DateTime.Now;
            else
                entity.StartDate = DateTime.Parse(dto.StartDate);
            if (String.IsNullOrEmpty(dto.EndDate))
                entity.EndDate = DateTime.MaxValue;
            else
                entity.EndDate = DateTime.Parse(dto.EndDate);

            if (!String.IsNullOrEmpty(dto.SrcSaleDocNo))
            {
                entity.SrcSaleDocNo = dto.SrcSaleDocNo;
                SaleContract saleContract = EntityUtils.GetDocEntity<SaleContract>(dto.SrcSaleDocNo);
                entity.SrcSale = saleContract.ID;
            }
            entity.QAExpireDate = DateTime.MaxValue;
            if (dto.ProjextMaster != null)
            {
                entity.ProjextMaster = EntityUtils.GetEntityByCode<Operators>(dto.ProjextMaster);
                if(entity.ProjextMaster == null) 
                {
                    throw new Exception($"项目经理[ProjextMaster]查找失败,Code[{dto.ProjextMaster.Code}]");
                }
                entity.ProjectManagerName = entity.ProjextMaster.Name;
            }
            entity.PlanTotalHours = 1;
            entity.Org = Context.LoginOrg;//组织
            entity.CostORG=EntityUtils.GetEntityByCode<Organization>(dto.CostORG);//成本组织
            entity.Department = EntityUtils.GetEntityByCode<Department>(dto.Department);
            entity.Customer = EntityUtils.GetEntityByCode<Customer>(dto.Customer);
            entity.ProjectType = ProjectClassifyEnum.GetFromValue(dto.ProjectType);
            entity.CanOpenBillingAmountRule = UFIDA.U9.CBO.Enums.CanOpenBillingAmountRuleEnum.QuantityRatio;
            entity.CanCarryCostRule = UFIDA.U9.CBO.Enums.CanCarryCostRuleEnum.QuantityRatio;

            //有效性
            if (dto.Effective == null)
            {
                entity.Effective = new UFIDA.U9.Base.PropertyTypes.Effective
                {
                    IsEffective = true,
                    EffectiveDate = DateTime.Now,
                    DisableDate = DateTime.MaxValue,
                };
            }
            else
            {
                entity.Effective = new UFIDA.U9.Base.PropertyTypes.Effective();
                entity.Effective.IsEffective=dto.Effective.IsEffective;
                entity.Effective.EffectiveDate = DateTime.Parse(dto.Effective.EffectiveDate);
                entity.Effective.DisableDate = DateTime.Parse(dto.Effective.DisableDate); 
            }

            //实体扩展字段
            if (dto.DescFlexField != null)
            {
                entity.DescFlexField = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegments();
                DTOUtils.DTOPropCopy(dto.DescFlexField, entity.DescFlexField);
            }
            
        }
    }

	#endregion
	
	
}